package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/boyane/chartroom/common/message"
	"github.com/boyane/chartroom/server/utils"
)

// 定义一个全局变量维护在线用户

var(
	OnlineUsers *OnlineUser
)

type OnlineUser struct {
	onlineUsers map[int]*User
}

func init() {
	OnlineUsers = &OnlineUser{
		onlineUsers: make(map[int]*User, 1024),
	}
}

// 添加用户
func (this *OnlineUser) AddOnlineUser(user *User) {
	this.onlineUsers[user.UserId] = user
}

// 删除用户
func (this *OnlineUser) DelOnlineUser(userId int) {
	delete(this.onlineUsers, userId)
}

// 查询所有在线用户
func (this *OnlineUser) GetAllOnlineUsers() map[int]*User {
	return this.onlineUsers
}

// 获取一个用户的连接
func (this *OnlineUser) GetOnlineUserById(userId int) *User{
	return this.onlineUsers[userId]
}

// 向所有用户发送用户上线消息
func (this *OnlineUser) NotifyUserOnlineMes(userId int){
	for k, v := range this.onlineUsers{
		if k == userId{ // 如果是自己就不发了
			continue
		}
		this.NotifyUsersMeOnline(v, userId)
	}
}

// 通知用户上线
func (this *OnlineUser) NotifyUsersMeOnline(user *User, userId int){
	var mes message.Message
	mes.Type = message.UserOnlineMesType
	// 组装通知消息结构
	var userOnlineMes message.UserOnlineMes
	userOnlineMes.UserId = this.onlineUsers[userId].UserId
	userOnlineMes.Status = message.Online
	userOnlineMes.UserName = this.onlineUsers[userId].UserName

	bytes, err := json.Marshal(userOnlineMes)
	if err != nil{
		fmt.Println("NotifyUsersMeOnline -> json.Marshal err =", err)
		return
	}
	mes.Data = string(bytes)

	bytes, err = json.Marshal(mes)
	if err != nil{
		fmt.Println("NotifyUsersMeOnline -> json.Marshal err =", err)
		return
	}
	ts := utils.Transfer{}
	ts.Conn = user.Conn
	err = ts.WritePkg(bytes)
	if err != nil{
		fmt.Println("NotifyUsersMeOnline -> ts.WritePkg err =", err)
		return
	}
}